//
//  HomePageReplyListViewController.m
//  ShowYork
//
//  Created by hxh on 2020/11/24.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "HomePageReplyListViewController.h"


#import "HomePageReplyItemModel.h"
#import "HomePageReplyListCell.h"

#import "HomePageReplyMainTitleCell.h"
@interface HomePageReplyListViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,HomePageReplyListCellDelegate,HomePageReplyMainTitleCellDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,assign)NSInteger pageIndex;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,assign)NSInteger total;

@property (nonatomic,assign)CGRect rect;
@property (nonatomic,strong)UILabel *noDataLb;

@property (nonatomic,strong)NSNumber *lastReplyId;

@property (nonatomic,strong)HomePageCommentItemModel *commentModel;

@end

@implementation HomePageReplyListViewController

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (instancetype)initWithLastReplyId:(NSNumber *)replyId{
    if (self = [super init]) {
        self.lastReplyId = replyId;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageIndex = 1;
    
    self.isHideNavBar = YES;

    [self setUI];
}

- (void)setUI{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    self.tableView.backgroundColor = [UIColor whiteColor];
    __weak typeof(self)weakSelf = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageIndex++;
        [weakSelf loadDataSource];
    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    self.tableView.mj_footer = footer;
    
    self.tableView.backgroundColor = RGBA(248, 248, 248, 1);
    
    self.noDataLb = [[UILabel alloc]init];
    self.noDataLb.text = @"暂无回复，快来抢沙发～";
    self.noDataLb.textColor = C153;
    self.noDataLb.font = font(12);
    [self.view addSubview:self.noDataLb];
    [self.noDataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    self.noDataLb.hidden = YES;
    
    if (self.lastReplyId.intValue != 0) {
        [self loadTargetSource];
    }
}

- (void)loadTargetSource{
    if (self.lastReplyId.intValue == 0) {
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"replyId"] = self.lastReplyId;
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetCommentReply];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetCommentReply) parames:param success:^(id responseObj) {
        if (responseObj[RESPONSE][@"reply"] != nil) {
            self.lastReplyModel = [HomePageReplyListModel mj_objectWithKeyValues:responseObj[RESPONSE][@"reply"]];
        }
        if (responseObj[RESPONSE][@"comment"] != nil) {
            self.commentModel = [HomePageCommentItemModel mj_objectWithKeyValues:responseObj[RESPONSE][@"comment"]];
        }
        [self loadDataSource];
     
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (void)requestDataWithCurrentModel:(HomePageCommentItemModel *)commentModel{
    self.commentModel = commentModel;
    [self loadDataSource];
}

- (void)loadDataSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetCommentReplyList];
    param[@"commentId"] = self.commentModel.id;
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"pageIndex"] = @(self.pageIndex);
    param[@"pageSize"] = @(10);
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetCommentReplyList) parames:param success:^(id responseObj) {
        
        
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        
        if (self.pageIndex == 1) {
            self.dataArray = [HomePageReplyListModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[HomePageReplyListModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        CGFloat bottom = self.tableView.mj_insetB;
        if ([responseObj[RESPONSE][LASTPAGE]boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            if (self.tableView.mj_footer.cl_height == 44.0f) {
                self.tableView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.tableView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            if (self.tableView.mj_footer.cl_height == 138.0f) {
                self.tableView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.tableView.mj_insetB = 44.0f;
                }
            }
        }
        if (self.lastReplyModel != nil && self.lastReplyModel.id != 0) {
            self.lastReplyModel.isDisplay = YES;
            __block NSInteger index = -1;
            [self.dataArray enumerateObjectsUsingBlock:^(HomePageReplyListModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.id isEqualToNumber:self.lastReplyModel.id] && !obj.isAdd) {
                    index = idx;
                    *stop = YES;
                }
            }];
           
            if (index != -1) {
                [self.dataArray removeObjectAtIndex:index];
            }
            if (!self.lastReplyModel.isAdd) {
                self.lastReplyId = @0;
                self.lastReplyModel.isAdd = YES;
                [self.dataArray insertObject:self.lastReplyModel atIndex:0];
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.lastReplyModel.isDisplay = NO;
                [self.tableView reloadRow:0 inSection:1 withRowAnimation:UITableViewRowAnimationAutomatic];
            });
        }

        [self.tableView reloadData];
        
        self.rect = [self.tableView rectForSection:0];
        
        [self hideDataLoadLoadState];

        self.total = [responseObj[RESPONSE][TOTAL] intValue];
        
    } failure:^(id error) {
        [self hideDataLoadLoadState];
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        self.pageIndex--;
        
    }];
}


- (void)sendReplyMessage:(NSString *)replyText originalMessage:(NSString *)originalText userInfoList:(NSArray *)userInfoList commentId:(NSNumber *)commentId{
  
    if (commentId.intValue == 0 && self.commentModel.id.intValue == 0) {
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:AddCommentReply];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"original"] = originalText;
    param[@"commentId"] = commentId.intValue == 0?self.commentModel.id:commentId;
    param[@"replyText"] = replyText;
    if (userInfoList.count > 0) {
        NSMutableArray *arr = [NSMutableArray array];
        [userInfoList enumerateObjectsUsingBlock:^(UserInfoModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [arr addObject:obj.id];
        }];
        param[@"mentionIds"] = arr.mj_keyValues;
        
        [MobClick event:@"comment_reply_@_count"];
    }
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddCommentReply) parames:param success:^(id responseObj) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"发送成功" duration:2 finishHandler:nil];
        HomePageReplyListModel *itemModel = [HomePageReplyListModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        [self.dataArray insertObject:itemModel atIndex:0];
        
        self.total++;
        NSString *title = @"";
        if (self.tableView.contentOffset.y >= CGRectGetMaxY(self.rect) + 44) {
            if (self.total >= 10000) {
                NSInteger count = self.total;
                if (count % 1000 == 0) {
                    count += 1;
                }
                title = [NSString stringWithFormat:@"%@w条回复",[RPAppManager notRounding:count/10000.0f afterPoint:1]];
            }else{
                title = [NSString stringWithFormat:@"%ld条回复",(long)self.total];
            }
        }
        if (self.showNavTitle) {
            self.showNavTitle(title);
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCommentItem" object:nil userInfo:@{@"data":self.dataArray.firstObject,@"status":@1}];
        
        self.noDataLb.hidden = self.dataArray.count != 0;
        CGFloat bottom = self.tableView.mj_insetB;
        if (self.total == self.dataArray.count) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            if (self.tableView.mj_footer.cl_height == 44.0f) {
                self.tableView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.tableView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            if (self.tableView.mj_footer.cl_height == 138.0f) {
                self.tableView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.tableView.mj_insetB = 44.0f;
                }
            }
        }

        [self.tableView reloadData];
        
        [MobClick event:@"comment_detail_send"];
        
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSString *title = @"";
    
    if (scrollView.contentOffset.y <= 0) {
        scrollView.contentOffset = CGPointMake(0, 0);
    }
    
    if (scrollView.contentOffset.y >= CGRectGetMaxY(self.rect) + 44) {
        
        if (self.total >= 10000) {
            NSInteger count = self.total;
            if (count % 1000 == 0) {
                count += 1;
            }
            title = [NSString stringWithFormat:@"%@w条回复",[RPAppManager notRounding:count/10000.0f afterPoint:1]];
        }else{
            title = [NSString stringWithFormat:@"%ld条回复",(long)self.total];
        }
    }
    if (self.showNavTitle) {
        self.showNavTitle(title);
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
   
    if (self.dataArray.count == 0) {
        return self.commentModel != nil?1:0;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    self.tableView.mj_footer.hidden = self.dataArray.count == 0;
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        HomePageReplyMainTitleCell *cell = [HomePageReplyMainTitleCell cellWithTableView:tableView];
        [cell setModel:self.commentModel];
        cell.delegate = self;
        return cell;
    }else{
        HomePageReplyListCell *cell = [HomePageReplyListCell cellWithTableView:tableView];
        [cell setModel:self.dataArray[indexPath.row]];
        cell.delegate = self;
        return cell;
    }
    return [UITableViewCell new];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 44)];
        lb.text = [NSString stringWithFormat:@"———  共%lu条回复  ———",self.total];
        lb.textColor = C35;
        lb.font = [UIFont boldSystemFontOfSize:14];
        lb.textAlignment = NSTextAlignmentCenter;
        lb.backgroundColor = RGBA(248, 248, 248, 1);
        return lb;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 44.0f;
    }
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

#pragma mark - HomePageReplyListCellDelegate
- (void)showUserInfoByUserId:(NSNumber *)userId{
    [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"userId":userId,@"loadType":@(1)} completion:nil];
}
- (void)removePostReplyById:(NSNumber *)replyId{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = replyId;
    param[@"md5"] = [RPAppManager md5StrWithApi:DeleteCommentReply];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(DeleteCommentReply) parames:param success:^(id responseObj) {
        NSInteger index = -1;
        HomePageReplyListModel *currentModel = nil;
        for (int i = 0; i < self.dataArray.count; i++) {
            HomePageReplyListModel *model = self.dataArray[i];
            if ([model.id isEqualToNumber:replyId]) {
                index = i;
                currentModel = model;
                break;
            }
        }
        
        if (index != -1) {
            [self.dataArray removeObjectAtIndex:index];
            if (self.dataArray.count == 0) {
                [self.tableView reloadData];
            }else{
                [self.tableView deleteRow:index inSection:1 withRowAnimation:UITableViewRowAnimationAutomatic];
            }
        }
        [WHToast showMessage:@"删除成功" duration:2 finishHandler:nil];
        
        self.noDataLb.hidden = self.dataArray.count != 0;
        CGFloat bottom = self.tableView.mj_insetB;
        if (self.total == self.dataArray.count) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            if (self.tableView.mj_footer.cl_height == 44.0f) {
                self.tableView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.tableView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            if (self.tableView.mj_footer.cl_height == 138.0f) {
                self.tableView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.tableView.mj_insetB = 44.0f;
                }
            }
        }
        
        if (self.dataArray.count > 0) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCommentItem" object:nil userInfo:@{@"data":self.dataArray.firstObject,@"status":@0}];
        }else{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteAllCommentReply" object:nil userInfo:@{@"data":currentModel.commentId}];
        }
    
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
- (void)reportPostReplyById:(NSNumber *)replyId{
    [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":self.navigationController,@"reportId":replyId ,@"reportType":@(0)} completion:nil];
}

- (void)doDissOrLikeWithStatus:(BOOL)status replyId:(NSNumber *)replyId{
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"type"] = @1;
    param[@"isTourist"] = status?@1:@2;
    param[@"evaluateType"] = @(3);
    param[@"postId"] = replyId;
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(DoDetailLike) parames:param success:^(id responseObj) {
            
        [MobClick event:@"reply_detail_like"];
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        __block NSInteger index = -1;
        [self.dataArray enumerateObjectsUsingBlock:^(HomePageReplyListModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.id isEqualToNumber:replyId]) {
                index = idx;
                *stop = YES;
            }
        }];
        if (index != -1) {
            HomePageReplyListModel *model = self.dataArray[index];
            NSInteger likeNum = model.likeNum.intValue;
            if (model.like) {
                likeNum--;
            }else{
                likeNum++;
            }
            model.likeNum = @(likeNum);
            model.like = !model.like;
            [self.tableView reloadRow:index inSection:1 withRowAnimation:UITableViewRowAnimationNone];
        }
        
        
    }];

}

#pragma mark - HomePageReplyMainTitleCellDelegate

- (void)reportPostCommentById:(NSNumber *)commendId{
    [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":self.navigationController,@"reportId":commendId ,@"reportType":@(0)} completion:nil];
}
- (void)removePostCommentById:(NSNumber *)commentId{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = commentId;
    param[@"md5"] = [RPAppManager md5StrWithApi:DeletePostComments];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(DeletePostComments) parames:param success:^(id responseObj) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteCommentItem" object:nil userInfo:@{@"data":self.commentModel}];
        [WHToast showMessage:@"删除成功" duration:2 finishHandler:nil];
        if (self.deleteComment) {
            self.deleteComment();
        }
        
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (void)showUserInfoById:(NSNumber *)userId{
    [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"userId":userId,@"loadType":@(1)} completion:nil];
}
- (void)sendCommentById:(NSNumber *)commentId{
    if (self.showSendCommentReply) {
        self.showSendCommentReply(commentId);
    }
}
- (void)doDissOrLikeWithStatus:(BOOL)status commentId:(NSNumber *)commentId{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"type"] = @1;
    param[@"isTourist"] = status?@1:@2;
    param[@"evaluateType"] = @(2);
    param[@"postId"] = commentId;
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(DoDetailLike) parames:param success:^(id responseObj) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCommentLikeStatus" object:nil userInfo:@{@"data":self.commentModel}];
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCommentLikeStatus" object:nil userInfo:@{@"data":self.commentModel}];
    }];
}
- (void)dealloc{
    
}
@end
